const fs = require("fs");
const path = require("path");

const _templateFolder = "demo";
const _exclude = ["common"];
const _root = "./../";
const _pPlace = `${_root}projects`;
const _templatePlace = `${_pPlace}/${_templateFolder}`;

const loggerWrapper = (msg) => console.warn(`\n ${msg} \n`);

// 返回 projects目录下除了 common 文件夹以外的其他目录作为 app
const getSubApps = () => {
  const projectsPath = path.resolve(__dirname, _pPlace);
  const apps = fs.readdirSync(projectsPath);
  return apps.filter((file) => {
    const current = path.join(projectsPath, file);
    const isDir = fs.statSync(current).isDirectory();
    return isDir && !_exclude.includes(file);
  });
};

const getPredefineApps = () => [
  "modern",
  "report",
  "report-json",
  "inline-vue",
  "watch",
  "open",
  "copy",
  "https",
  "verbose"
];

const initNpmConfigParams = (args) => {
  if (args instanceof Object) {
    Object.keys(args).forEach((key) => {
      if (args[key] === true) {
        process.env[`npm_config_${key}`] = true;
      }
    });
  }
};

const { exec, execSync, spawn } = require("child_process");

function runCommand(cmdArr, callback) {
  console.time("run-command");
  (function next(i) {
    if (i === cmdArr.length) {
      console.log(`执行完毕`);
      console.timeEnd("run-command");
      callback && callback();
      return;
    }
    console.log(`执行命令 ${cmdArr[i]}`);
    runSpawn(cmdArr[i], () => {
      next(i + 1);
    });
  })(0);
}

function runSpawn(command, callback) {
  const res = spawn(command, { stdio: "inherit", shell: true });
  res.stdout &&
    res.stdout.on("data", (data) => {
      console.log("stdout", data);
    });
  res.stderr &&
    res.stderr.on("data", (data) => {
      console.log("stderr", data);
    });
  res.on("close", () => {
    callback && callback();
  });
}

function runExec(command, callback) {
  return exec(
    command,
    (function () {
      return function (err, data, stderr) {
        if (!callback) return;

        callback(err, data, stderr);
      };
    })(callback)
  );
}

function runSync(command) {
  try {
    return {
      data: execSync(command).toString(),
      err: null,
      stderr: null
    };
  } catch (error) {
    return {
      data: null,
      err: error.stderr.toString(),
      stderr: error.stderr.toString()
    };
  }
}

module.exports = {
  _root,
  _pPlace,
  _templatePlace,
  _templateFolder,
  initNpmConfigParams,
  getSubApps,
  getPredefineApps,
  loggerWrapper,
  runCommand,
  runSync,
  runSpawn,
  runExec
};
